package han.cirno.corrupt

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import han.cirno.corrupt.components.cnn.LarvaWrapper.Companion.fromStream
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException
import java.net.HttpURLConnection
import java.util.regex.Pattern

/**
 * Instrumented test, which will execute on an Android device.
 *
 * @see [Testing documentation](http://d.android.com/tools/testing)
 */
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {

    @Test
    suspend fun downloadTest(){
    }

    @Test
    @Throws(IOException::class)
    fun cnnTest() {
        val applicationContext = ApplicationProvider.getApplicationContext<Context>()
        val assets = applicationContext.assets
        val testPictureInputStream = assets.open("test.gif")
        val bitmap = BitmapFactory.decodeStream(testPictureInputStream)
        testPictureInputStream.close()
        _cnnTest(bitmap)
    }

    fun _cnnTest(bitmap: Bitmap): String {
        val applicationContext = ApplicationProvider.getApplicationContext<Context>()
        val assets = applicationContext.assets
        val netInputStream = assets.open("net.larva")
        val larvaWrapper = fromStream(netInputStream)
        checkNotNull(larvaWrapper)
        val predict = larvaWrapper.predict(bitmap)
        Log.i("LarvaTest", predict)
        return predict
    }

    val okHttpClient = OkHttpClient()
    fun getCheckCodeBitmap(token:String):Bitmap{
        val request = Request.Builder().url("http://jwgl.fafu.edu.cn/$token/CheckCode.aspx").build()
        val newCall = okHttpClient.newCall(request)
        val response = newCall.execute()
        val decodeStream = BitmapFactory.decodeStream(response.body!!.byteStream())
        return decodeStream
    }

    fun getCheckCode(token: String):String{
        return _cnnTest(getCheckCodeBitmap(token))
    }

    @Test
    @Throws(IOException::class)
    fun networkTest() {
        try {
            val build = Request.Builder().url("http://jwgl.fafu.edu.cn/").get().build()
            val newCall = okHttpClient.newCall(build)
            val response = newCall.execute()
            //println(response.body!!.string())
            if (response.code != HttpURLConnection.HTTP_OK) {
                return
            }
            val url = response.request.url.toString()
            val tokenMatcher = Pattern.compile("\\(\\w+\\)").matcher(url)
            tokenMatcher.find()
            val token=tokenMatcher.group(0)
            val checkCode = getCheckCode(token!!)
            val postForm = Request.Builder().url("http://jwgl.fafu.edu.cn/$token/default2.aspx")
                .post(
                    FormBody.Builder()
                        .add("__VIEWSTATE","dDwtMTM0OTIyMDA2Nzs7PiISqN1gnNqgqFWWKvzntrB+oNfb")
                        .add("txtUserName", "3245002077")
                        .add("TextBox2", "&&Chen123")
                        .add("txtSecretCode", checkCode)
                        .add("RadioButtonList1", "学生")
                        .add("Button1", "")
                        .add("lbLanguage", "")
                        .add("hidPdrs", "")
                        .add("hidsc", "").build()
                )
                .build()
            val postCall = okHttpClient.newCall(postForm)
            val postResponse = postCall.execute()
            val returnBody=postResponse.body!!.string()
            println(postResponse)
            println(returnBody)
            val alertMather=Pattern.compile("(?<=(alert\\(')).+?(?='\\))").matcher(returnBody)
            println("CODE:::::$checkCode")
            if(alertMather.find()){
                val err = alertMather.group(0)
                println("Alert:$err")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    val errorPassword="密码错误，您还有4次尝试机会！如忘记密码，请与教务处联系!"
    val errorUserName="用户名不存在或未按照要求参加教学活动！！"
    val errorCode="验证码不正确！！"

}